<%--
     Copyright 2010 mazhao.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
    under the License.
    Document   : detail
    Created on : Oct 8, 2010, 10:39:19 PM
    Author     : mazhao
--%>

<%@page contentType="text/html" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link type="text/css" href="<%=request.getContextPath()%>/stylesheet/smoothness/jquery-ui-1.8.6.custom.css"
          rel="stylesheet"/>
    <script type="text/javascript" src="<%=request.getContextPath()%>/script/jquery-ui-1.8.6.custom.js"></script>
    
    <script type="text/javascript">
        //DEBUG = true;

        var currentProductId = <s:property value="detail.id"/>;

        /**
         * Main JavaScript Function.
         * @param data
         */
        $(document).ready(function() {
            /**
             * add action for Buy link.
             */
            $("#putcartLink").click(function() {
                $.log("before put cart");
                $.log("<%= request.getContextPath()%>/front/onthefly/putcart.action");
                $.log($("#accountForPutcart").val());
                $.log($("#productIdForPutcart").val());

                $.post("<%= request.getContextPath()%>/front/onthefly/putcart.action",
                {"account": $("#accountForPutcart").val() , "productId": $("#productIdForPutcart").val()},
                        afterPutcart,
                        "json");
            });

            /**
             * load images of current product.
             */

            loadImages();

            /**
             * submit question click
             */
            $("#submitQuestion").click(submitProductQuestion);

            /**
             * load all the questions
             */
            loadQuestions();


            /**
             * answer dialog
             */
            $("#answerDiv").dialog({
                autoOpen: false,
                height: 300,
                width: 500,
                modal: true,
                buttons:{
                    "Answer":  submitAnswerDialog,
                    "Cancel": function(){
                        $( this ).dialog( "close" );
                    }
                },
                close: function() {
				    $.log("dialog closed");
			    }
            });
        });

        /**
         * after buy show success information.
         */
        function afterPutcart(data) {
            $.log("receive data:" + data);
            $.log(data.onTheFlyMessage);
            $.log(data.account);
            $.log(data.onTheFlyStatus);

            if (data.onTheFlyStatus == true) {
                $.log("put cart successfully");
                $.jGrowl(data.onTheFlyMessage);
            }
        }

        function loadImages() {
            $.post("<%= request.getContextPath()%>/front/onthefly/listimages.action",
            {"productId": currentProductId},
                    loadImageImpl,
                    "json");
        }

        function loadImageImpl(data) {
            $.log("begin loadImageImpl");

            $.log("image size:" + data.images.length);
            for (var i = 0; i < data.images.length; i++) {
                $.log("image path:" + data.images[i]);
                var trStr =
                        "<img src='<%=request.getContextPath()%>/front/productimage.action?path=" + data.images[i] + "' alt='item image'/>";
                $("td#imageTd").append(trStr);
            }
            //$("td#imageTd").children().first().remove();
            $.log("end loadImageImpl");
        }

        function submitProductQuestion() {
            $.log("begin submit product question");
            var question = $("#question").val();
            var username = $("#questionUsername").val();
            $.log("question " + question );
            $.log("username " + username );
            $.post("<%=request.getContextPath()%>/front/onthefly/addquestion.action",
                   {"productId": currentProductId, "question": question, "username": username},
                   afterSubmitProductQuestion,
                   "json"
                    );
        }

        function afterSubmitProductQuestion(data) {
            $.log("status :" + data.onTheFlyStatus);
            $.log("message:" + data.onTheFlyMessage);
            if(data.onTheFlyStatus) {
                loadQuestions();
            }
        }

        function loadQuestions() {
            $.post("<%=request.getContextPath()%>/front/onthefly/listquestion.action",
                   {"productId": currentProductId},
                   afterLoadQuestions,
                   "json"
                    );
        }

        function safeHTML(s) {
            return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        }

        function afterLoadQuestions(data) {
            $.log("question count:" + data.questions.length);

            var cnt = "";
            for(var i = 0 ; i < data.questions.length; i++) {
                var pq = data.questions[i];
                var questionId = pq.id;
                var question = pq.question;
                var username = pq.username;
                var ans = "";
                $.log("answer count for " + safeHTML(question) + " is " + pq.answers.length);
                for( var j = 0; j < pq.answers.length; j++) {
                    var pa = pq.answers[j];
                    ans += pa.answer + " by " + pa.username + "<br/>"
                }

                // @TODO: Security XSS
                question = safeHTML(question);
                ans = safeHTML(ans);

                cnt += "<tr><td>" + questionId + ":" + question + " by " + username +
                        "<button class='alt' onclick='showAnswerDialog("+ questionId +")'>Answer</button></td>" +
                        "<td>" + ans + "</td></tr>"
            }

            $("table#questionListTable tr").remove();

            $("table#questionListTable").append(cnt);
        }

        function showAnswerDialog(questionId) {
            $.log("enter showAnswerDialog with " + questionId);
            $("#answerQuestionId").val(questionId);
            $.log("after set hidden value");
            $( "#answerDiv" ).dialog( "open" );
        }

        function submitAnswerDialog() {
            var qid = $("#answerQuestionId").val();
            var as = $("#answer").val();
            var un = $("#answerUsername").val();
            $.log("question id " + qid);
            $.log("answer:" + as);
            $.log("answer user name:" + un);

            $.post("<%=request.getContextPath()%>/front/onthefly/answerquestion.action",
                    {"questionId":qid, "answer": as, "username": un},
                    afterSubmitAnswerDialog,
                    "json"
                    );
            $(this).dialog("close");
        }
        function afterSubmitAnswerDialog(data) {
            $.log("after submit answer dialog")
            $.log("status " + data.onTheFlyStatus);
            $.log("message " + data.onTheFlyMessage);
            loadQuestions();
        }
    </script>
    <title>Product Detail</title>
</head>
<body>
<div class="span-15 alt" style="margin-left:0px">
    Product Information:
    <table>
        <tr>
            <td colspan="2" id="imageTd">

            </td>
        </tr>
        <tr>
            <td>ID</td>
            <td><s:property value="detail.id"/></td>
        </tr>
        <tr>
            <td>Catalog</td>
            <td><s:property value="detail.catalogId"/></td>
        </tr>
        <tr>
            <td>Name</td>
            <td><s:property value="detail.name"/></td>
        </tr>

        <tr>
            <td>Description</td>
            <td><s:property value="detail.description"/></td>
        </tr>
        <tr>
            <td>Original Price</td>
            <td><s:property value="detail.originalPrice"/></td>
        </tr>

        <tr>
            <td>Member Price</td>
            <td><s:property value="detail.memberPrice"/></td>
        </tr>

        <tr>
            <td>Special Price</td>
            <td><s:property value="detail.specialPrice"/></td>
        </tr>

        <tr>
            <td>Discount</td>
            <td><s:property value="detail.discount"/></td>
        </tr>
        <tr>
            <td>Point</td>
            <td><s:property value="detail.point"/></td>
        </tr>
        <tr>
            <td>Star</td>
            <td><s:property value="detail.star"/></td>
        </tr>
    </table>
</div>
<div class="span-3 last alt colborder" id="submitForm">
    <s:form namespace="/front" action="putcart" id="putcartForm" theme="simple">
        <s:hidden name="productId" id="productIdForPutcart"/>
        Account&nbsp;&nbsp;<s:select name="account" id="accountForPutcart"
                                     list="#{'1':'1','2':'2','3':'3','4':'4','5':'5'}"/>
        &nbsp;&nbsp;&nbsp;&nbsp;<s:a href="#" id="putcartLink">Buy</s:a>
    </s:form>
</div>
<div id="questionAndAnswer" class="span-15 alt">
    Question & Answer:
    <div id="questionListDiv">
        <!-- question table for append -->
        <table id="questionListTable">
        </table>
        <table id="questionSubmitTable">
            <tr>
                <td>Question:</td>
                <td>
                    <textarea id="question" rows="2" cols="20" style="height:60px; width:300px"></textarea>
                </td>
            </tr>
            <tr>
                <td>User Name:</td>
                <td>
                    <input type="text"  id="questionUsername" style="width:300px;" >
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <button id="submitQuestion" name="Submit">Submit Question</button>
                </td>
            </tr>

        </table>
    </div>
    <div id="answerDiv">
        <input type="hidden" id="answerQuestionId"/>
        <table>
            <tr>
                <td>Answer</td>
                <td><textarea id="answer" rows="2" cols="20" style="height:60px; width:300px"></textarea></td>
            </tr>
            <tr>
                <td>User Name:</td>
                <td>
                    <input type="text"  id="answerUsername" style="width:300px;" >
                </td>
            </tr>
        </table>
    </div>
</div>


</body>
</html>
